/**
 * Created by zxr on 16/11/10.
 */
var net = require('net');
var events = require('events').EventEmitter;
var channel = new events();

channel.clients = {};
channel.subscriptions = {};
channel.on('join',function(id,client){
	console.log(id);
	console.log(client);
	this.clients[id] = client;
	this.subscriptions[id] = function(sendId,message){
		if (id != sendId) {
			this.clients[id].write(message);
		}
	}
	this.on('broadcast',this.subscriptions[id]);
});
channel.on('error',function(err){
	console.log(err)
})


 net.createServer(function(client){
	var id = client.remoteAddress + ":" + client.remotePort;
	client.on('connect',function(){
		console.log(id);
		channel.emit('join',id,client);
	})
	client.on('data',function(data){
		data = data.toString();
		console.log(data);
		channel.emit('broadcast',id,data)
	})
}).listen('8888');
